import axios from "axios";
import { YundocApi } from "./yundocRequest";

const appkey = "dingwnocxslvwnl4onqg";
const appsecret =
  "L73Jkiuwz8zG8X7be2o7NvrWTkOEKhlsjArbGHhz40ryKJOZqrGBpbNjpG1oX-gN";
const baseURL = "https://oapi.dingtalk.com";

export default class DingtalkRequest {
  private static instance: DingtalkRequest;
  private static axiosInstance = axios.create({
    baseURL: "https://oapi.dingtalk.com",
    timeout: 10000,
    headers: {
      "Content-Type": "application/json",
    },
  });

  constructor() {}

  public static getInstance() {
    if (!DingtalkRequest.instance) {
      DingtalkRequest.instance = new DingtalkRequest();
    }
    return DingtalkRequest.instance;
  }

  public async get(url: string, params: any) {
    const res = await DingtalkRequest.axiosInstance.get(url, { params });
    return res.data;
  }

  public async post(url: string, data: any) {
    const res = await DingtalkRequest.axiosInstance.post(url, data);
    return res.data;
  }

  /**
   * 获取钉钉开放平台access_token
   * @returns
   */
  public async getAccessToken() {
    let params = {
      appkey: appkey,
      appsecret: appsecret,
    };
    const res: any = this.get("/gettoken", { params });
    return res.data.access_token;
  }

  /**
   * 查询部门用户列表
   * @returns
   */
  public async getDeptUserList(accessToken: any, deptId: string) {
    const res: any = this.get(
      "/topapi/user/listsimple?access_token=" + accessToken,
      {
        dept_id: deptId,
        cursor: 0,
        size: 100,
      }
    );

    return res.data.result.list;
  }

  /**
   * 查询钉钉子部门信息以及用户信息并同步到云文档
   *  @param accessToken 授权token
   *  @param parentDeptId 父级部门id
   *  @param docParentDeptId 云文档父级部门id
   */
  public async recursionSyncSubDeptAndUser(
    accessToken: any,
    parentDeptId: string,
    docParentDeptId: string
  ) {
    let request = new YundocApi();
    // 查询钉钉部门详情
    let parentDept: any = this.get("/topapi/v2/department/get", {
      access_token: accessToken,
      id: parentDeptId,
    });
    // 查询钉钉子部门id列表
    let subDeptIdListRes: any = this.post(
      "/topapi/v2/department/listsubid?access_token=" + accessToken,
      { dept_id: parentDeptId }
    );
    let subDeptIdList = subDeptIdListRes.result.dept_id_list;
    // 查询云文档子部门列表
    let yundocDeptList: any = request.apiBranch(docParentDeptId);
    // 查询云文档相同名称部门
    let yundocDeptFilterList: any = yundocDeptList.filter(
      (item: { name: any }) => {
        return item.name === parentDept.name;
      }
    );
    let yundocSubDept: any = {};
    // 部门不存在则新增，存在则引用
    if (yundocDeptFilterList.length === 0) {
      // 新增部门
      let createDeptBody = {
        name: parentDept.name,
        source: "sync",
        third_platform_id: "1",
        third_union_id: "1",
        weight: 0,
      };
      yundocSubDept = request.apiNewBranch(docParentDeptId, createDeptBody);
    } else {
      // 引用部门
      yundocSubDept = yundocDeptFilterList[0];
    }
    // 查询钉钉部门用户列表
    let deptUserList: any = this.getDeptUserList(accessToken, parentDeptId);
    // 云文档部门新增用户
    deptUserList.foreach(
      (user: { name: any; userid: any; account_id: number }) => {
        // 创建用户
        let addUserBody = {
          account: user.name,
          nick_name: user.name,
          password: "123456",
          third_platform_id: "1",
          third_union_id: user.userid,
        };
        request.createUser(addUserBody);
        // 部门用户绑定
        let deptUserBindBody = {
          set_def_dept: true,
          weight: 0,
        };
        request.addAccount(yundocSubDept.id, user.account_id, deptUserBindBody);
        // 激活用户
        let enableUserBody = {
          account_ids: [user.account_id],
        };
        request.enterpriseMembers(enableUserBody);
      }
    );
    // 子部门不为空
    if (subDeptIdList.length > 0) {
      // 遍历子部门id
      for (let i = 0; i < subDeptIdList.length; i++) {
        // 查询子部门详情和用户信息
        this.recursionSyncSubDeptAndUser(
          accessToken,
          subDeptIdList[i],
          yundocSubDept.id
        );
      }
    }
  }
}
